package com.mm.learn.juc;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * volatile 轻量级的同步机制
 * 1、可见性
 * 2、不保证原子性
 * 保证原子性方法：
 * （1）synchronized
 * (2)AtomicInteger
 * 3、禁止指令重排 有序性
 */
public class VolatileTest {

    volatile int num = 0;

    //不保证原子性方法
    public void add() {
        num++;
    }

    //保证原子性
    AtomicInteger atomicInteger = new AtomicInteger();


    public void addByAtomic() {
        atomicInteger.getAndIncrement();
    }

    public static void main(String[] args) {
        Object o1 = true;
        System.out.println(o1);//
        Object o2;
        if (true)
            o2 = new Integer(1);
        else
            o2 = new Double(2.0);
        System.out.println(o2);//
        //不保证原子性演示
        VolatileTest test = new VolatileTest();
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                for (int j = 1; j <= 1000; j++) {
                    test.add();
                    test.addByAtomic();
                  /*  try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }*/
                }
            }, String.valueOf(i)).start();
        }
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        //如果是原子性值为10000 否则说明不是原子性
        System.out.println(Thread.currentThread().getName() + test.num);
        System.out.println(Thread.currentThread().getName() + test.atomicInteger);
    }

}
